const router = require('express').Router()
const validateToken = require('../../../common/validateToken')
const status_code = require('../../../common/status_code')
const db = require('../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../common/bee/bee')

router.post('/add-comment', async (req, resp) => {
  // 错误处理
  function handleError(errCode, error) {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  const {
    news_id,
    parent_comment_id,
    parent_comment_user_id,
    reply_comment_id,
    reply_comment_user_id,
    comment_level,
    content,
  } = req.body
  if (
    !Bee.StringUtils.isNotBlank(content) ||
    !Bee.StringUtils.isNumber(news_id) ||
    !Bee.StringUtils.isNumber(parent_comment_id) ||
    !Bee.StringUtils.isNumber(parent_comment_user_id) ||
    !Bee.StringUtils.isNumber(reply_comment_id) ||
    !Bee.StringUtils.isNumber(reply_comment_user_id) ||
    !Bee.StringUtils.isNumber(comment_level) ||
    (comment_level !== 1 && comment_level !== 2)
  )
    return handleError(10003, '参数错误')

  // 判断是否有当前栏目
  const [findNewsError, findNewsSuccess] = await to(
    db.query('SELECT count(*) FROM news WHERE id = ?', [news_id])
  )
  if (findNewsError || !findNewsSuccess) return handleError(-1, findNewsError)
  if (findNewsSuccess[0]['count(*)'] !== 1) handleError(-1, '系统错误') // 没有栏目就响应错误

  const [addCommentError, addCommentSuccess] = await to(
    db.query(
      'INSERT INTO comment (user_id, user_name, news_id, parent_comment_id, parent_comment_user_id, reply_comment_id, reply_comment_user_id, comment_level, content, created_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())',
      [
        validateTokenSuccess.id,
        validateTokenSuccess.account,
        news_id,
        parent_comment_id,
        parent_comment_user_id,
        reply_comment_id,
        reply_comment_user_id,
        comment_level,
        content,
      ]
    )
  )
  if (addCommentError || !addCommentSuccess)
    return handleError(-1, addCommentError)
  if (addCommentSuccess.affectedRows > 0) {
    // 获取评论条数
    const [getTotalError, Total] = await to(
      db.query(
        'SELECT count(*) FROM comment WHERE news_id = ? AND comment_level = 1',
        [news_id]
      )
    )
    if (getTotalError || !Total) return handleError(-1, getTotalError)
    console.log(Total[0]['count(*)'])
    // 更新资讯评论次数字段
    const [updateNewsCommentCountError, updateNewsCommentCount] = await to(
      db.query('UPDATE news SET comment_count=? WHERE id = ?', [
        Total[0]['count(*)'],
        news_id,
      ])
    )
    if (updateNewsCommentCountError || !updateNewsCommentCount)
      return handleError(-1, updateNewsCommentCountError)

    return resp.json({
      code: 0,
      msg: status_code[0],
      data: {
        id: addCommentSuccess.insertId,
      },
    })
  }
  return handleError(-1, '系统错误')
})

module.exports = router
